package com.mht.cfa.server.config;

import com.mht2017.common.config.SearchConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;

/**
 * @author yutong.xiao
 */
public final class ConfigLoader {

    private static Logger logger = LoggerFactory.getLogger(ConfigLoader.class);

    private static boolean isInited = false;

    public static void init() {
        if (isInited) {
            return;
        }

        try {
            SearchConfiguration config = new SearchConfiguration();
            File file = new File(Config.CONFIG_FILE_PATH);
            if (file.exists()) {
                logger.info(String.format("读取配置文件: '%s'", file.getAbsolutePath()));
                try {
                    config.addConfiguration(new XMLConfiguration(file.toURI().toURL()));
                } catch (ConfigurationException e) {
                    logger.error("加载外部配置出错", e);
                }
            } else {
                logger.info(String.format("没有找到自定义配置文件: '%s'", file.getAbsolutePath()));
            }
            try {
                URL resource = ConfigLoader.class.getClassLoader().getResource(Config.CONFIG_FILE_PATH);
                logger.info(String.format("加载缺省配置: '%s'", resource));
                config.addConfiguration(new XMLConfiguration(resource));
            } catch (ConfigurationException e) {
                logger.error("加载缺省配置出错", e);
            }
            loadConfig(config);
            isInited = true;
        } catch (Exception e) {
            logger.error("加载配置文件失败", e);
            System.exit(1);
        }
    }

    private static void loadConfig(SearchConfiguration config) {
        try {
            Config.springBootPort = config.getInt("application.port");
        } catch (Exception e) {
            logger.error("加载配置出错", e);
        }
    }

}
